"""
序列化类
"""
# 返回 Author 部分字段，列表
from rest_framework import serializers
from rest_framework_mongoengine import serializers as mongoserializers

from authorshow.models.models import Author, Paper, PubsEmbedded, Venue


class ListAuthorSerializer(mongoserializers.DynamicDocumentSerializer):
    class Meta:
        model = Author
        fields = ('id', 'name', 'position', 'n_pubs', 'orgs', 'tags', 'h_index')


# 返回 Author 所有字段数据，明细
def author_create_or_update(instance: Author, validated_data):
    instance.name = validated_data.get('name')
    instance.h_index = validated_data.get('h_index')
    instance.orgs = validated_data.get('orgs')
    if validated_data.get('tags') is not None:
        tags = instance.tags
        if tags is not None:
            tags.clear()
        for tag in validated_data.get('tags'):
            tags.create(w=tag.get('w'), t=tag.get('t'))
    instance.n_citation = validated_data.get('n_citation')
    instance.position = validated_data.get('position')
    instance.chiname = validated_data.get('chiname')
    instance.chiorgs = validated_data.get('chiorgs')
    instance.save()


class AuthorSerializer(mongoserializers.DynamicDocumentSerializer):
    id = serializers.CharField()

    class Meta:
        model = Author
        fields = '__all__'
        # exclude = ('h_index', ) # 不展示某些内容，不可与 fields 属性同时使用
        # depth = 2  # 可选，适用于 ReferenceField & ListField

    def create(self, validated_data):
        author = Author()
        author.id = validated_data.get('id')
        author_create_or_update(instance=author, validated_data=validated_data)
        return author

    def update(self, instance, validated_data):
        """更新，不包含 id，n_pubs，pubs 字段更新"""
        author_create_or_update(instance=instance, validated_data=validated_data)
        return instance


class PaperSerializer(mongoserializers.DynamicDocumentSerializer):
    id = serializers.CharField()

    class Meta:
        model = Paper
        fields = '__all__'

    # def create(self, validated_data):

    # def update(self, instance, validated_data):


class VenueSerializer(mongoserializers.DynamicDocumentSerializer):
    class Meta:
        model = Venue
        fields = '__all__'


class PubsEmbeddedSerializer(mongoserializers.DynamicDocumentSerializer):
    class Meta:
        model = PubsEmbedded
        fields = '__all__'
